package com.vcit.framework.web.service;

import com.vcit.common.core.domain.entity.TStudent;

import com.vcit.common.core.domain.model.StudentLoginUser;
import com.vcit.common.exception.user.UserPasswordNotMatchException;
import com.vcit.common.utils.ServletUtils;
import com.vcit.framework.security.context.AuthenticationContextHolder;
import com.vcit.system.service.student.ITStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.vcit.common.core.domain.entity.SysUser;
import com.vcit.common.core.domain.model.LoginUser;
import com.vcit.common.enums.UserStatus;
import com.vcit.common.exception.ServiceException;
import com.vcit.common.utils.MessageUtils;
import com.vcit.common.utils.StringUtils;
import com.vcit.system.service.ISysUserService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * 用户验证处理
 *
 * @author dff
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;


    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ITStudentService studentService;

    /**
     * 通用登录
     */
    private UserDetails doBaseUserDetails(String username) {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);
        return createLoginUser(user);
    }

    /**
     * 学生登录逻辑
     */
    private UserDetails doStuUserDetails(String username) {
        TStudent student = studentService.selectStudentByName(username);
        // todo 学生状态判断
        if (student == null) {
            throw new ServiceException(MessageUtils.message("学生信息不存在！！！"));
        }
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String idCards = usernamePasswordAuthenticationToken.getCredentials().toString();
        // todo 匹配姓名身份证
        if (StringUtils.isNull(idCards) && idCards.length() != 6) {
            throw new ServiceException(MessageUtils.message("请正确输入身份证号"));
        }

        // 成功颁发token
        String stuIdCard = student.getIdCard();
        if (StringUtils.isNull(stuIdCard)) {
            throw new ServiceException(MessageUtils.message("未录入学生身份证号"));
        }

        if (stuIdCard.endsWith(idCards)) {
            // todo 将需要的字段封装进学生登录实体，后续会序列化到jwttoken中
            StudentLoginUser studentLoginUser = new StudentLoginUser(student, Collections.EMPTY_SET);

            return studentLoginUser;


        } else {
            throw new ServiceException(MessageUtils.message("学生身份未找到"));
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        HttpServletRequest request = ServletUtils.getRequest();
        String userType = request.getHeader("User-Type");
        // 走学生逻辑
        if ("stu".equals(userType)) {
            return doStuUserDetails(username);
        } else if (userType == null || "tea".equals(userType)) {
            // 走老师逻辑
            return doBaseUserDetails(username);
        } else {
            // 非法操作
            throw new UsernameNotFoundException("非法操作，不能识别的登录策略。");
        }

    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
